package ms.jung.andorid.caldavtodo;

import java.util.ArrayList;
import java.util.List;

import ms.jung.andorid.caldavtodo.account.Account;
import ms.jung.andorid.caldavtodo.account.AccountAdapter;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.ResourceCursorAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
/**
 * Lists Activity to chose Account and pick list
 * 
 * TODO: 
 * 
 * @author Felix Martens <cheefy13@gmail.com>
 * 
 */
public class CalDavToDoLists  extends ListActivity {

	/// Some Definitions
		private static final int EDIT_DELETE = 1;
		private static final int ADD = 2;
		private ArrayList<Account> accounts = new ArrayList<Account>();
		


		@Override
		public void onCreate(Bundle savedInstanceState)
		{
			/// Setup Activity and View
			super.onCreate(savedInstanceState);
			setContentView(R.layout.lists);
			final ListView listView =  getListView();

			
			//create a task list
			/*ContentValues values = new ContentValues();
			values.put(TaskContract.TaskLists.ACCOUNT_NAME, "TESTACCOUNT");
			values.put(TaskContract.TaskLists.ACCOUNT_TYPE, TaskContract.LOCAL_ACCOUNT);
			values.put(TaskContract.TaskLists.NAME, "TESTLIST 002");     
			values.put(TaskContract.TaskLists.COLOR, 0xffff0000);     
			values.put(TaskContract.TaskLists.VISIBLE, 1);     
			getContentResolver().insert(TaskContract.TaskLists.CONTENT_URI.buildUpon()
				.appendQueryParameter(TaskContract.TaskLists.ACCOUNT_NAME, "TESTACCOUNT")
				.appendQueryParameter(TaskContract.TaskLists.ACCOUNT_TYPE, TaskContract.LOCAL_ACCOUNT)
				.appendQueryParameter(TaskContract.CALLER_IS_SYNCADAPTER, "true")
				.build(), values);
			*/
			/// Create cursor to transfer data from SQLite to ListView 
			/// Fields from the database are linked to the text fields of the views.
	
			//First get accounts and all lists
			 Cursor c = managedQuery(TaskContract.TaskLists.CONTENT_URI , new String[] {"_id",TaskContract.TaskLists.ACCOUNT_NAME,TaskContract.TaskLists.ACCOUNT_TYPE,TaskContract.TaskLists.NAME}, null, null,"");  
			
			//Set ListView for lists									
			String[] from = {
					"_id",
					TaskContract.TaskLists.NAME
				};  

				int[] to = {
						R.id.sqlID,
						R.id.listname,			
				}; 		

				/// Create Cursor Adapter
				final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.rowlist, c, from, to);
				listView.setAdapter(adapter);
				
				//List to make Accounts distinct and count the list
				ArrayList AccountName = new ArrayList();
				int count = 0;
				//Build the CustomAdapter Array for the Spinner
				if (c != null) {
				    if (c.moveToFirst()) {
				        do { String tmp = c.getString(c.getColumnIndex(TaskContract.TaskLists.ACCOUNT_NAME));
				        	if (tmp != null){ count++;
				        		if ( ! AccountName.contains(tmp) )
				        			{AccountName.add(tmp);
				        			accounts.add(new Account(c.getString(c.getColumnIndex(TaskContract.TaskLists.ACCOUNT_NAME)),c.getString(c.getColumnIndex(TaskContract.TaskLists.ACCOUNT_TYPE)),1));}
				        		else
				        		{accounts.set(AccountName.indexOf(tmp),
				        								new Account(c.getString(c.getColumnIndex(TaskContract.TaskLists.ACCOUNT_NAME)),
				        											c.getString(c.getColumnIndex(TaskContract.TaskLists.ACCOUNT_TYPE)),
				        											accounts.get(AccountName.indexOf(tmp)).getCount()+1
				        										)
				        						);
				        		
				        		}
				        	}
				        } while (c.moveToNext());
				    }
				}  
		      
				accounts.add(new Account(getString(R.string.allaccounts),"",count));
				final Spinner spinner = (Spinner) findViewById(R.id.accounts);
				final AccountAdapter AccountAdapter = new AccountAdapter(this,R.id.rowAccountLayout,accounts);
				//AccountAdapter.setDropDownViewResource(R.id.rowAccountDropDown);
				spinner.setAdapter(AccountAdapter);
				spinner.setSelection(accounts.size()-1);
				
				spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

		            public void onItemSelected(AdapterView<?> adapterView, View view,
		                    int position, long id) {
		              Account account = AccountAdapter.getItem(position);
		              Cursor c2;
		              //If all accounts are chosen
		                if ( account.getName().equals(getString(R.string.allaccounts)) ){
		                	c2 = managedQuery(TaskContract.TaskLists.CONTENT_URI , new String[] {"_id",TaskContract.TaskLists.NAME}, null, null,"");  			
		                }else
		                {
		                	c2 = managedQuery(TaskContract.TaskLists.CONTENT_URI.buildUpon().appendQueryParameter(TaskContract.TaskLists.ACCOUNT_NAME, account.getName()).build() 
		                			, new String[] {"_id",TaskContract.TaskLists.NAME}, null  , null,"");  
		        			
		                }
		                // Update the adapter of the ListView

		                ListView listView = getListView();
		               adapter.changeCursor(c2);
		               adapter.notifyDataSetChanged();
		               listView.scrollBy(0, 0);
		            }
		            public void onNothingSelected(AdapterView<?> adapter) { 
		            	spinner.setSelection(accounts.size()-1);
		            }
		        });

			listView.setOnItemClickListener(new OnItemClickListener(){

				public void onItemClick(AdapterView<?> arg0, View arg1,
						int position, long id) {
					//Opening Tasklist with id
					 Intent intent = new Intent(getBaseContext(),CalDavToDoTasks.class);	
					TextView t = (TextView)listView.getChildAt(position).findViewById(R.id.sqlID);
					 intent.putExtra("list_id",t.getText().toString());
						startActivity(intent);
					
				}
				
				
			});	
		
			
		}
		

		

		
		 
		
		  
		  
		  

}
